package org.fly.jingwei.exception;

import org.fly.jingwei.bean.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author leo.jie (weixiao.me@aliyun.com)
 * @version 1.0
 * @organization bigdata
 * @website https://www.jielongping.com
 * @date 2020/5/31 2:05 下午
 * @since 1.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(JingWeiSysException.class)
    public ResponseUtil<Object> sysServiceExceptionHandler(JingWeiSysException e) {
        logger.error("精卫大数据平台温馨提示:" + e.getErrorMsg() + " >>>>>>>>>>>>>>>>>>>");
        return ResponseUtil.failed().message(e.getErrorMsg());
    }

    @ExceptionHandler(Exception.class)
    public ResponseUtil<Object> exceptionHandler(Exception e) {
        logger.error(e.getMessage());
        e.printStackTrace();
        return ResponseUtil.failed().message("你把系统玩炸了 >>>>>>>>>>>>>>>>>>>>>>>>>>");
    }

    @ExceptionHandler({MethodArgumentNotValidException.class})
    public ResponseUtil<Object> validException(MethodArgumentNotValidException e) {
        FieldError fieldError = e.getBindingResult().getFieldError();
        String errorMsg = "参数校验异常！";
        if (null != fieldError) {
            errorMsg = fieldError.getDefaultMessage();
            logger.error("参数校验异常:{}({})", errorMsg, fieldError.getField());
        }
        return ResponseUtil.failed().message(errorMsg);
    }

    @ExceptionHandler({BindException.class})
    public ResponseUtil<Object> bindException(BindException e) {
        FieldError fieldError = e.getBindingResult().getFieldError();
        String errorMsg = "必填校验异常！";
        if (null != fieldError) {
            errorMsg = fieldError.getDefaultMessage();
            logger.error("必填校验异常:{}({})", errorMsg, fieldError.getField());
        }
        return ResponseUtil.failed().message(errorMsg);
    }

}
